package comtgl.demo.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ImageDownloader {

    public static void main(String[] args) {
        // 示例URL列表
        List<String> imageUrls = List.of(
                "https://example.com/image1.jpg",
                "https://example.com/image2.png",
                "https://example.com/image3.gif"
        );

        String zipFilePath = "downloaded_images.zip";

        try {
            downloadImagesAndCreateZip(imageUrls, zipFilePath);
            System.out.println("ZIP文件创建成功: " + zipFilePath);
        } catch (IOException e) {
            System.err.println("处理过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 下载多个图片并创建ZIP文件
     *
     * @param imageUrls   图片URL列表
     * @param zipFilePath ZIP文件保存路径
     * @throws IOException 如果发生IO错误
     */
    public static void downloadImagesAndCreateZip(List<String> imageUrls, String zipFilePath) throws IOException {
        // 创建临时目录用于存储下载的图片
        Path tempDir = Files.createTempDirectory("image_downloads_");

        try {
            List<Path> downloadedFiles = downloadImages(imageUrls, tempDir);
            createZipFile(downloadedFiles, zipFilePath);

            // 清理临时文件
            cleanupTempFiles(downloadedFiles);
        } finally {
            // 删除临时目录
            Files.deleteIfExists(tempDir);
        }
    }

    /**
     * 下载图片到指定目录
     *
     * @param imageUrls 图片URL列表
     * @param tempDir   临时目录
     * @return 下载的文件路径列表
     * @throws IOException 如果发生IO错误
     */
    private static List<Path> downloadImages(List<String> imageUrls, Path tempDir) throws IOException {
        List<Path> downloadedFiles = new ArrayList<>();

        for (int i = 0; i < imageUrls.size(); i++) {
            String url = imageUrls.get(i);
            try {
                // 生成唯一的文件名
                String fileName = "image_" + (i + 1) + getFileExtension(url);
                Path outputPath = tempDir.resolve(fileName);

                downloadImage(url, outputPath);
                downloadedFiles.add(outputPath);

                System.out.printf("已下载 %d/%d: %s%n", i + 1, imageUrls.size(), url);
            } catch (IOException e) {
                System.err.printf("下载失败 %s: %s%n", url, e.getMessage());
            }
        }

        return downloadedFiles;
    }

    /**
     * 从URL下载单个图片
     *
     * @param imageUrl   图片URL
     * @param outputPath 输出路径
     * @throws IOException 如果发生IO错误
     */
    private static void downloadImage(String imageUrl, Path outputPath) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        try (InputStream in = connection.getInputStream();
             OutputStream out = Files.newOutputStream(outputPath)) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }

    /**
     * 创建ZIP文件
     *
     * @param filePaths   文件路径列表
     * @param zipFilePath ZIP文件保存路径
     * @throws IOException 如果发生IO错误
     */
    private static void createZipFile(List<Path> filePaths, String zipFilePath) throws IOException {
        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
            for (Path filePath : filePaths) {
                File file = filePath.toFile();
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOut.putNextEntry(zipEntry);

                try (FileInputStream fis = new FileInputStream(file)) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = fis.read(buffer)) != -1) {
                        zipOut.write(buffer, 0, bytesRead);
                    }
                }

                zipOut.closeEntry();
            }
        }
    }

    /**
     * 清理临时文件
     *
     * @param filePaths 文件路径列表
     */
    private static void cleanupTempFiles(List<Path> filePaths) {
        for (Path filePath : filePaths) {
            try {
                Files.deleteIfExists(filePath);
            } catch (IOException e) {
                System.err.printf("无法删除临时文件 %s: %s%n", filePath, e.getMessage());
            }
        }
    }

    /**
     * 从URL获取文件扩展名
     *
     * @param url URL
     * @return 文件扩展名（包括点号）
     */
    private static String getFileExtension(String url) {
        int lastIndex = url.lastIndexOf('.');
        return lastIndex != -1 ? url.substring(lastIndex) : ".jpg";
    }
}